<script setup lang="ts">
/**
 * 指标数据页面
 * 按周期（小时、日、月、年）和时间区间查询指标的累加或表头数据
 */
import { ElLink, ElPageHeader } from 'element-plus'
import SearchForm from './components/SearchForm.vue'
import type { TableList } from './types'
import { PERIODS } from './types'
import TableLists from '@/components/TableLists/TableLists.vue'
import ListsPagination from '@/components/ListsPagination/ListsPagination.vue'
import FullscreenModal from '@/components/FullscreenModal/FullscreenModal.vue'
import ViewChartLine from '@/components/view-chart-line/index.vue'

import { uuid } from '@/utils'
import { PAGING } from '@/constant'
import type { TableColumn } from '@/types'

import { dataManagementApi } from '@/api'

const loading = ref(true)
const lists = ref<TableList[]>([])

const pagination = reactive({
  pageNum: 1,
  pageSize: PAGING.PARAMS.pageSize,
  total: 0,
})

const query: {
  keyword: string
  period: PERIODS
  time: string | [string, string]
} = reactive({
  keyword: '',
  period: PERIODS.DATE,
  time: ['', ''] as [string, string],
})

const visible = ref(false)
const pageHeaderTitle = ref('')
const lineOption = computed(() => {
  return {
    legend: {
      show: false,
    },
    toolbox: {
      show: true,
      feature: {
        dataZoom: {
          yAxisIndex: 'none',
          title: {
            zoom: '区域缩放',
            back: '区域缩放还原',
          },
        },
        dataView: { readOnly: false, title: '数据视图' },
        magicType: {
          type: ['line', 'bar'],
          title: {
            line: '切换为折线图',
            bar: '切换为柱状图',
          },
        },
        restore: {
          title: '还原',
        },
        saveAsImage: {
          title: '保存为图片',
        },
      },
    },
    // dataZoom: [
    //   { type: 'slider', start: 0, end: 50 },
    //   { type: 'inside', start: 0, end: 50 }
    // ]
  }
})
const indicator = ref({
  indicatorName: '',
  indicatorCode: '',
  dataTime: '',
})
const indicatorData = ref([])
const lineDataset = computed(() => {
  const data = indicatorData.value as {
    dataTime: string
    val: number
  }[]
  return {
    source: [
      data.map(v => v.dataTime),
      data.map(v => v.val),
    ],
  }
})

// TODO
const request = computed(() => {
  const { period } = toValue(query)
  const {
    loadIndicatorDayPage,
    loadIndicatorHourPage,
    loadIndicatorMonthPage,
    loadIndicatorYearPage,
  } = dataManagementApi
  let rq = loadIndicatorDayPage
  switch (period) {
    case PERIODS.HOUR:
      rq = loadIndicatorHourPage
      break
    case PERIODS.MONTH:
      rq = loadIndicatorMonthPage
      break
    case PERIODS.YEAR:
      rq = loadIndicatorYearPage
      break
    default:
      rq = loadIndicatorDayPage
  }
  return rq
})
const requestIndicatorData = computed(() => {
  const { period } = toValue(query)
  const {
    loadDayResourceListByIndicator,
    loadHourResourceListByIndicator,
    loadMonthResourceListByIndicator,
  } = dataManagementApi
  let rq = null
  switch (period) {
    case PERIODS.DATE:
      rq = loadHourResourceListByIndicator
      break
    case PERIODS.MONTH:
      rq = loadDayResourceListByIndicator
      break
    case PERIODS.YEAR:
      rq = loadMonthResourceListByIndicator
      break
  }
  return rq
})
const columns: TableColumn<TableList>[] = [
  { key: uuid(), label: '指标名称', prop: 'indicatorName' },
  {
    key: uuid(),
    label: '测点点位号',
    prop: 'indicatorCode',
    render({ row }) {
      if (/\d{2}:00/.test(row.dataTime)) {
        return row.indicatorCode
      }
      return h(
        ElLink,
        {
          underline: false,
          type: 'primary',
          onClick: () => {
            indicator.value = {
              ...row,
            }
            pageHeaderTitle.value
              = `${row.indicatorName} 指标数据图表`
            visible.value = true
            getIndicatorData()
          },
        },
        () => row.indicatorCode,
      )
    },
  },
  { key: uuid(), label: '数据时间', prop: 'dataTime' },
  { key: uuid(), label: '数据值', prop: 'val' },
  // { key: uuid(), label: '数据来源', prop: 'source' }
]
async function queryLists() {
  const { pageNum, pageSize } = pagination
  loading.value = true

  let startTime, endTime
  try {
    if (Array.isArray(query.time)) {
      [startTime, endTime] = query.time
    }
    else {
      startTime = endTime = query.time
    }
    const { data } = await request.value(
      pageNum,
      pageSize,
      {
        indicatorName: query.keyword,
        startTime,
        endTime,
      },
    )
    if (data) {
      lists.value = data.records
      pagination.total = data.total
    }
    else {
      lists.value = []
      pagination.total = 0
    }
  }
  finally {
    loading.value = false
  }
}
async function getIndicatorData() {
  loading.value = true
  const { indicatorCode, dataTime } = indicator.value
  try {
    const { data } = await requestIndicatorData.value!(
      indicatorCode,
      dataTime,
    )
    if (data) {
      indicatorData.value = data.map((v: any) => {
        return {
          dataTime: v.dataTime,
          val: v.val,
        }
      })
    }
  }
  finally {
    loading.value = false
  }
}
async function clickSearch() {
  pagination.pageNum = 1
  await nextTick()
  queryLists()
}

onMounted(() => {
  queryLists()
})
</script>

<template>
  <div
    class="padding-sm flex-direction relative flex align-end container"
  >
    <TableLists
      :loading="loading"
      :lists="lists"
      :columns="columns"
      :show-toolbox="true"
    >
      <template #actions>
        <SearchForm v-model="query" @search="clickSearch" />
      </template>
    </TableLists>
    <ListsPagination
      v-model:page-num="pagination.pageNum"
      v-model:page-size="pagination.pageSize"
      :total="pagination.total"
      @current-change="queryLists"
      @size-change="queryLists"
    />
    <FullscreenModal v-model="visible">
      <ElPageHeader title="返回" @back="visible = false">
        <template #content>
          <span>{{ pageHeaderTitle }}</span>
        </template>
      </ElPageHeader>
      <ViewChartLine
        style="height: calc(100% - 30px)"
        :mark-line="[]"
        :option="lineOption"
        :dataset="lineDataset"
        :is-area-shadow="true"
      />
    </FullscreenModal>
  </div>
</template>
